$(document).ready(function(){
    //创建goeasy，订阅当前登录用户的警报频道
    var goEasy = new GoEasy({
        appkey:"BS-7beb6aa3e5f54e9b8c407932aee0ccae"
    });
    //获取当前登录用户信息
    $.ajax({
        url: CONTEXT_PATH + "/user/getCurrentUser.do",
        type: "get",
        dataType: "json",
        success: function(user){
            if(user){
                //订阅个人警报频道
                goEasy.subscribe({
                    channel:"userAlarmChannel:"+user.usId,
                    //接收到消息后，弹出提示
                    onMessage: function(message){
                        $.messager.show({ title: '警报提示', msg: message.content, timeout: 0, showType: "slide" ,width: 340,height: 240});
                    }
                });
                //订阅为处理警报频道
                goEasy.subscribe({
                    channel:"alarmChannel",
                    //接收到消息后，查询未处理的警报数量
                    onMessage: function(){
                        //查询未处理的警报并显示
                        checkAlarm();
                    }
                });
                //订阅登陆状态频道
                var processName = $("#processName").val();
                goEasy.subscribe({
                    channel:"userLoginChannel:"+user.usId+processName,
                    onMessage:function(message){
                        $.messager.show({ title: '登陆提示', msg: message.content, timeout: 0, showType: "slide" ,width: 280,height: 180});
                    }
                });
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
    //加载未处理警报
    checkAlarm();
    //警报图标点击按钮绑定
    $("#alarmSign").click(function(){
        var alarmList = $("#alarmSign").data("alarmList");
        if(alarmList.length > 0){
            if(alarmList[0].alarmCategory == 1){
                openAlarmList("1");
            }else{
                openAlarmList("2");
            }
        }
    });

    //初始化用户信息下拉框
    $("#userInfo").tooltip({
        position: 'bottom',
        content: '<ul class="userOptionTool" >\n' +
        '                        <li><a href="#" onclick="companyInfo()" class="easyui-linkbutton" style="background: transparent; border: none">公司信息</a></li>\n' +
        '                        <li><a href="#" onclick="userInfo()" class="easyui-linkbutton" style="background: transparent; border: none">个人信息</a></li>\n' +
        '                        <li><a href="#" onclick="editPassword()" class="easyui-linkbutton" style="background: transparent; border: none">修改密码</a></li>\n' +
        '                        <li><a href="#" onclick="loginOut()" class="easyui-linkbutton" style="background: transparent; border: none">退出系统</a></li>\n' +
        '         </ul>',
        showEvent:'mouseenter',
        hideEvent:'onblur',
        onShow: function(){
            $(this).tooltip('tip').css({
                backgroundColor: '#f8f8f8',
                borderColor: '#dedede'
            });
        }
    });
    $("#userInfo").click(function(event){
        $("#userInfo").tooltip("show");
        event.stopPropagation();
    });
    $(document).click(function(){
        closeUserOption();
    });


    //将_menus处理成map型
    for (var i = 0; i < _menus.length; i++){
        menusMap[_menus[i].meId] = _menus[i];
    }

    //系统设置点击
    $("#systemConfig").click(function(){
        updateNav(this);
        $(".rootNav li a.selected").removeClass("selected");
    })

    //顶部菜单点击事件
    $("#rootNav li").each(function () {
        $(this).click(function () {
            updateNav(this);
        });
    });

    //导航切换
    $(".menuson li").click(function(){
        $(".menuson li.active").removeClass("active");
    });

    //头部菜单点击切换效果
    $(".rootNav li").click(function(){
        $(".rootNav li a.selected").removeClass("selected");
        $(this).find("a").addClass("selected");
    })

    //设置时间
    // showTime();

    //初始化左侧菜单
    $($(".rootNav li a").get(0)).trigger("click");
    //初始化公司logo
    var companyLogoId = $('#companyLogo_').val();
    if(companyLogoId){
        $.ajax({
            url: CONTEXT_PATH + "/commonFile/getFileUrlById.do?id=" + companyLogoId,
            type: "get",
            success: function (data) {
                var url = data.message;
                if(url != "" && url != null){
                    $('#companyLogoImgInit_').attr('src',url);
                }
            }
        });
    }
});
//关闭用户下拉列表
function closeUserOption(){
    $("#userInfo").tooltip("hide");
}

//查询未处理警报，并显示
function checkAlarm(){
    $.ajax({
        url: CONTEXT_PATH + "/alarmSign/getUnresolveAlarm.do",
        type: "get",
        dataType: "json",
        success: function(data){
            if(data){
                try {
                    var total = data.total;
                    var alarmList = data.rows;
                    $("#alarmSign").data("alarmList",alarmList);
                    $("#alarmSign-inner").html(total);
                    if(total == 0){
                        $("#alarmSign-inner").removeClass("alarmSign-inner");
                        $("#alarmSign-inner").empty();
                    }else{
                        $("#alarmSign-inner").addClass("alarmSign-inner");
                    }
                    if(total >= 10){
                        $("#alarmSign-inner").addClass("bigData");
                        $("#alarmSign-inner").removeClass("superBigData");
                    }else if(total >= 100){
                        $("#alarmSign-inner").addClass("superBigData");
                        $("#alarmSign-inner").removeClass("bigData");
                    }else {
                        $("#alarmSign-inner").removeClass("bigData");
                        $("#alarmSign-inner").removeClass("superBigData");
                    }
                }catch (e) {
                    console.log(e);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}

//查看公司信息
function companyInfo(){
    layout("公司信息", CONTEXT_PATH+"/company/toCompanyInformation.do", "", true);
}

//查看和修改个人信息
function userInfo(){
    layout("个人信息",CONTEXT_PATH+"/user/toUserInformation.do","",true);
}


//点击修改密码
function editPassword(){
    $("#password").dialog({
        title: '修改密码',
        width: 360,
        height: 220,
        iconCls:"icon-xgmm",
        modal: true,
        closed: true,
        buttons:[{
            text:"修改",
            iconCls:"icon-role-state-ok",
            handler:function(){
                doEditPassword();
            }
        },{
            text:"取消",
            iconCls:"icon-role-state-no",
            handler:function(){
                $('#password').dialog('close');
            }
        }]
    });
    $('#password').window('open');
    clearForm("passwordForm");
};



//退出系统提示框
function loginOut() {
    $.messager.confirm('系统提示', '您确定要退出系统吗?', function(r) {
        if (r) {
            $.ajax({
                url: CONTEXT_PATH + "/userLogin/logout.do",
                type: "post",
                dataType: "json",
                cache: false,
                async: false,
                success: function(data){
                    if(data.code == 'PC_200'){
                        location.href = CONTEXT_PATH;
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    location.href = CONTEXT_PATH;
                }
            });
        }
    });
}

/**
 *
 */
function updateNav(obj){
    //获取此li的菜单ID，用此ID获取菜单
    var menuId = $(obj).attr("menuId");
    var data = menusMap[menuId];
    clearNav();
    if(data.children == undefined || data.children.length == 0){
        $(".leftNav-v2").panel({width: 1});
        $(".easyui-layout").layout("resize");
    }else{
        $(".leftNav-v2").panel({width: 180});
        $(".easyui-layout").layout("resize");
    }
    if(data.href != ""){
        layout(data.name , CONTEXT_PATH + data.href, data.iconCls, true);
        return;
    }
    addNav(data.children);
    initLeftMenu();
}

/**
 * 清空左侧菜单
 */
function clearNav(){
    var pp = $('#wnav').accordion('panels');

    for (var i=pp.length-1;i>=0;i--) {
        var t = $('#wnav').accordion('getPanel', i).panel('options').title;
        $('#wnav').accordion('remove', t);
    }
}

/**
 * 动态加载左侧菜单
 */
function addNav(data){
    $.each(data, function(i, sm) {
        var menulist = "";
        //若2级菜单有子菜单
        if(sm.children != null && sm.children.length > 0){
            menulist += '<div title="'+sm.name+'" data-options="iconCls:'+sm.iconCls+'" ><ul class="menuson">';
            $.each(sm.children, function(j, o) {
                menulist += '<li><cite></cite><a url="'+ CONTEXT_PATH + o.href +'" title="'+ o.name +'" iconCls="'+ o.iconCls +'">'+ o.name +'</a><i></i></li>';
            });
            menulist += '</ul></div>';
        }

        $('#wnav').accordion('add', {
            title : sm.name,
            border: false,
            content : menulist,
            iconCls : sm.iconCls,
            selected: false,
        });
    });
}

/**
 * 初始化左侧菜单
 */
function initLeftMenu(){
    //左侧菜单点击事件
    $(".menuson li").each(function(){
        $(this).click(function(){
            $(".menuson li").removeClass("selected");
            $(this).addClass("selected");
            var url = $(this).find("a").attr("url")
            var title = $(this).find("a").attr("title")
            var iconCls = $(this).find("a").attr("iconCls")
            layout(title, url, iconCls, true);
        });
    });
}

/**
 * 执行修改密码
 */
function doEditPassword(){
    var params = $("#passwordForm").serialize();
    $("#passwordForm").form("submit",{
        cache:false,
        data: params,
        url: CONTEXT_PATH + "/userLogin/modify.do",
        onSubmit:function() {
            return $(this).form("validate");
        },
        success:function(data) {
            var obj = JSON.parse(data);
            messager(obj);
            $('#password').dialog('close');
        }
    });
}


/***
 * 显示时间工具
 * @autour 谢泽鹏
 */
function showTime(){
    var Digital = new Date()
    var year = Digital.getYear() + 1900;
    var month = Digital.getMonth();
    var date = Digital.getDate();
    var day = Digital.getDay();
    var hours = Digital.getHours()
    var minutes = Digital.getMinutes()
    var seconds = Digital.getSeconds()

    month = parseInt(month)+ 1

    var daycn, dayen;
    switch(day){
        case 0:
            daycn = "星期天";
            dayen = "Sun.";
            break;
        case 1:
            daycn = "星期一";
            dayen = "Mon.";
            break;
        case 2:
            daycn = "星期二";
            dayen = "Tue.";
            break;
        case 3:
            daycn = "星期三";
            dayen = "Wed.";
            break;
        case 4:
            daycn = "星期四";
            dayen = "Thu.";
            break;
        case 5:
            daycn = "星期五";
            dayen = "Fri.";
            break;
        case 6:
            daycn = "星期六";
            dayen = "Sat.";
            break;
    }

    if(month <= 9){
        month = "0" + month;
    }
    if(date <= 9){
        date = "0" + date;
    }
    if(hours <= 9){
        hours = "0" + hours;
    }
    if (minutes<=9){
        minutes = "0" + minutes;
    }
    if (seconds<=9){
        seconds = "0" + seconds
    }

    var message = "";
    if(parseInt(hours) >= 0 && parseInt(hours) <= 6){
        message = "早上好！";
    }
    if(parseInt(hours) > 6 && parseInt(hours) <= 12){
        message = "上午好！";
    }
    if(parseInt(hours) > 12 && parseInt(hours) <= 18){
        message = "下午好！";
    }
    if(parseInt(hours) > 18 && parseInt(hours) <= 23){
        message = "晚上好！";
    }

    document.getElementById('mydate').innerHTML = year + "年" + month + "月" + date + "日" + "&nbsp;" + hours + ":" + minutes +  ":"  + seconds + "&nbsp;" + daycn + "&nbsp;" + message + "&nbsp;&nbsp;";
    setTimeout("showTime()", 1000)
}

//警报弹窗弹出时，查看警报
function openAlarmList(id){
    var title = "起重警示";
    if(id == 2){
        title = "扬尘警示"
    }
    layout(title, CONTEXT_PATH + "/alarmSign/index.do?id=" + id + "&alarmStatus=1", "icon-online-err", true);
}

/**
 * 打开项目查看窗口
 */
function openProjectViewWindow(option){
    option = $.extend({}, option, {
        onClose:function(){
            $("#projectWindow").window("body").html("");
        },
        onBeforeClose:function(){
            //刷新面板
            refreshFrame();
        }
    });
    $("#projectWindow").window(option);
    $("#projectWindow").window("open");
}

/**
 * 打开窗口(办理任务)
 */
function openTaskWindow(option){
    option = $.extend({}, option, {
        onOpen: function () {
            loading('流程加载中，请稍后。。。', 'taskWindow');
        },
        onClose: function(){
            $("#taskWindow").window("body").html("");
        },
        onBeforeClose: function(){
            refreshFrame();
        }
    });
    $("#taskWindow").window(option);
    $("#taskWindow").window("open");
}

/**
 * 查到节点
 * @param element
 */
function disLoading(element) {
    if(null != element && "" != element){
        $("#" + element).find(".datagrid-mask").remove();
        $("#" + element).find(".datagrid-mask-msg").remove();
        return;
    }
    $(".datagrid-mask").remove();
    $(".datagrid-mask-msg").remove();
}





/**
 * 关闭窗口
 * @param option
 */
function closeProjectViewWindow(){
    $("#projectWindow").window("close");
}


/**
 * 关闭窗口(办理任务)
 * @param option
 */
function closeTaskWindow(){
    $("#taskWindow").window("close");
}



/**
 * 选择头部菜单
 */
function toSelectMenu(menuObj,menuId,titleSon,args){
    //头部菜单切换效果
    $(".rootNav li a.selected").removeClass("selected");
    $(menuObj).find("a").addClass("selected");
    var data = menusMap[menuId];
    clearNav();
    if(data.children == undefined || data.children.length == 0){
        $(".leftNav-v2").panel({width: 1});
        $(".easyui-layout").layout("resize");
    }else{
        $(".leftNav-v2").panel({width: 180});
        $(".easyui-layout").layout("resize");
    }
    if(data.href != ""){
        layout(data.name , CONTEXT_PATH + data.href, data.iconCls, true);
        return;
    }
    addNav(data.children);
    initLeftMenu();
    //打开指定左侧菜单
    var pp = $('#wnav').find('.panel');
    $(pp).each(function (index, domEle) {
        var sonText = $(this).find(".panel-body").children('div').attr('title');
        if(titleSon == sonText){
            $("#wnav").accordion('select',index);
            var childLis = $(this).find(".panel-body").find('li');
            $(childLis).each(function (index, domEle) {
                var childTit = $(this).find("a").attr('title');
                if(childTit == sonText){
                    var currUrl = $(this).find("a").attr('url');
                    var currCls = $(this).find("a").attr('iconcls');
                    //起重机械警报
                    if(args == 'craneAlarm'){
                        currUrl = currUrl + '?alarmCategory=1'
                    }
                    //扬尘警报
                    if(args == 'dustAlarm'){
                        currUrl = currUrl + '?alarmCategory=2'
                    }
                    //项目类别为房建
                    if(args == 'fangjian'){
                        currUrl = currUrl + '?prTypeFromJump=1'
                    }
                    //项目类别为市政
                    if(args == 'shizheng'){
                        currUrl = currUrl + '?prTypeFromJump=2'
                    }
                    //项目类别为市政
                    if(args == 'shizheng'){
                        currUrl = currUrl + '?prTypeFromJump=2'
                    }
                    //扬尘设备数量
                    if(args == 'dustTotal'){
                        currUrl = currUrl + '?deviceType=dust'
                    }
                    //起重机械设备数量
                    if(args == 'craneTotal'){
                        currUrl = currUrl + '?deviceType=crane'
                    }
                    //视频设备数量
                    if(args == 'videoTotal'){
                        currUrl = currUrl + '?deviceType=video'
                    }
                    layout(sonText , currUrl, currCls, true);
                }
            })
        }
    })
}

/**
 * 修改公司logo
 * @param url
 */
function updateLogo(url){
    $('#companyLogoImgInit_').attr('src',url);
}